package com.snailct.bpp.service.core.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by huangxa on 2016/7/18.
 */
public class XmlUtil {
    public static Map<String,String> getReqParams(String xml){
        Map<String,String> rtnMap = new HashMap<String, String>();
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
            Document doc = builder.parse(inputStream);
            Element root = doc.getDocumentElement();

            NodeList nodeList = root.getChildNodes();
            for(int i=0;i<nodeList.getLength();i++){
                Node node = nodeList.item(i);
                if(node.getNodeName().equals("body")){
                    NodeList reqParamsNodes = node.getChildNodes();
                    for(int z=0;z<reqParamsNodes.getLength();z++){
                        Node reqParams = reqParamsNodes.item(z);
                        NodeList reqParamsNodePair = reqParams.getChildNodes();
                        for(int j=0;j<reqParamsNodePair.getLength();j++){
                            Node reqPair = reqParamsNodePair.item(j);
                            NodeList params = reqPair.getChildNodes();
                            String fieldName = null;
                            String fieldValue = null;
                            for(int k=0;k<params.getLength();k++){
                                Node param = params.item(k);
                                if(param.getNodeName().equals("fieldName")){
                                    fieldName = param.getTextContent();
                                }else if(param.getNodeName().equals("fieldValue")){
                                    fieldValue = param.getTextContent();
                                }
                                System.out.println("结点名称:"+param.getTextContent());
                                rtnMap.put(fieldName,fieldValue);
                            }

                        }
                    }

                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e){
            e.fillInStackTrace();
        } catch (IOException e){
            e.fillInStackTrace();
        }
        return rtnMap;
    }
}
